package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.exception.LogicException;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.query.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper ;


    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void insert(Employee employee, Long[] ids) {
        Md5Hash newPassword = new Md5Hash(employee.getPassword(), employee.getName(), 1);
        System.out.println(newPassword);
        employee.setPassword(newPassword.toString());
        employeeMapper.insert(employee);
        if(ids!=null && ids.length>0){
            for (Long roleId : ids) {
                employeeMapper.insertRelation(employee.getId(),roleId);
            }
        }
    }

    @Override
    public Employee selectOne(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> selectAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public void update(Employee employee, Long[] ids) {
        employeeMapper.updateByPrimaryKey(employee);
        employeeMapper.deleteRelation(employee.getId());
        if(ids!=null && ids.length>0){
            for(Long roleId : ids){
                employeeMapper.insertRelation(employee.getId(),roleId );
            }
        }
    }

    @Override
    public PageInfo<Employee> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize() );
        List<Employee> list = employeeMapper.queryForList(qo);
        return new PageInfo<Employee>(list);
    }

    @Override
    public Employee login(String username, String password) {
        if(!StringUtils.hasText(username)){
            throw new LogicException("用户名不能为空");
        }
        if(!StringUtils.hasText(password)){
            throw new LogicException("密码不能为空");
        }
        Employee employee = employeeMapper.selectByUsernameAndPassword(username, password);
        if(employee==null){
            throw new LogicException("用户名或密码错误");
        }
        if(!employee.isStatus()){
            throw new LogicException("您的账号已经被禁了");
        }
        return employee;
    }

    @Override
    public void updateNewPassword(String oldPassword, String newPassword) {
        Employee employee = UserContext.getCurrentUser();
        Md5Hash oldPassword2 = new Md5Hash(oldPassword, employee.getName());
        Long id = employee.getId();
        String password = employee.getPassword();
        if (!password.equals(oldPassword2.toString())) {
            throw new RuntimeException("旧密码不符,请重新输入");
        }
        Md5Hash md5Hash = new Md5Hash(newPassword, employee.getName());
        employeeMapper.updateNewPassword(md5Hash.toString(),id );
    }

    @Override
    public void resetPassword(String newPassword, Long id) {
        String name = employeeMapper.selectByPrimaryKey(id).getName();
        Md5Hash md5Hash = new Md5Hash(newPassword,name);
        employeeMapper.updateNewPassword(md5Hash.toString(),id );
    }

    @Override
    public void batchDelete(Long[] ids) {
        employeeMapper.batchDelete(ids);
    }

    @Override
    public Employee selectByName(String name) {
        Employee employee = employeeMapper.selectByName(name);
        return employee;
    }

    @Override
    public Workbook exportXls() {
        //创建excel文件
         Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet("员工表");
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");
        //查询员工数据
        List<Employee> employees = employeeMapper.selectAll();
        for(int i = 0 ; i < employees.size() ; i++){
            Employee employee = employees.get(i);
            row = sheet.createRow(i + 1);
            //设置内容到单元格中
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge());
        }
        return wb;
    }

    @Override
    public void importXls(MultipartFile file) throws IOException {
        HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
        HSSFSheet sheet = wb.getSheetAt(0);
        int lastRowNum = sheet.getLastRowNum();
        for(int i =1 ; i<= lastRowNum ; i++){
            HSSFRow row = sheet.getRow(i);
            String name = row.getCell(0).getStringCellValue();
            if(!StringUtils.hasLength(name.trim())){
                return ;
            }
            Employee employee = new Employee();
            employee.setName(name);
             employee.setEmail(row.getCell(1).getStringCellValue());
            Cell cell = row.getCell(2);
            //获取数值类型的单元格内容
            if(cell.getCellType()==CellType.NUMERIC ){
                employee.setAge((int)cell.getNumericCellValue());
            }else{
                employee.setAge(Integer.valueOf(cell.getStringCellValue()));
            }
             employee.setPassword("1");
             this.insert(employee,null );
        }


    }

    @Override
    public List<Employee> selectByRoleSn(String... sns) {
        return employeeMapper.selectByRoleSn(sns);
    }
}
